﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Syspetro.Core;
using Syspetro.Core.HttpService;
using System;
using System.Collections.Generic;

namespace Syspetro.Aliyun
{
    public class SMSService : ISMSService
    {
        private readonly string address = "http://api.smsbao.com";
        private readonly SMSBaoOptions baoOptions;

        private readonly Dictionary<string, string> codes = new()
        {
            { "30", "错误密码" },
            { "40", "账号不存在" },
            { "41", "余额不足" },
            { "43", "IP地址限制" },
            { "50", "内容含有敏感词" },
            { "51", "手机号码不正确" },
        };

        public SMSService()
        {
            baoOptions = new SMSBaoOptions();
            InternalApp.Configuration.Bind("SMSBaoOptions", baoOptions);
            if (baoOptions == null) baoOptions = new SMSBaoOptions();
        }

        public int GetPerLimit()
        {
            return baoOptions.PerLimit;
        }

        public int GetPerLimitHours()
        {
            return baoOptions.PerLimitHours;
        }

        public int GetValidTime()
        {
            return baoOptions.ValidTime;
        }

        public (bool status, string msg) Notify(string mobile, string content, string code = "888888", bool wsms = false)
        {
            if (!baoOptions.Enabled) return (false, "服务暂停");

            try
            {
                if (mobile.StartsWith("86"))
                    mobile = mobile[2..];
                if (string.IsNullOrEmpty(content))
                    content = string.Format(baoOptions.Templete, code, baoOptions.ValidTime);

                var (status, response) = Http.Instance.Get(address, $"sms?u={baoOptions.AppKey}&p={baoOptions.AppSecret}&m={mobile}&c={content}");

                if (status)
                {
                    var code_response = response;

                    var reason = codes.TryGetValue(code_response, out var code_msg) ? $"{code_response}:{code_msg}" : "未知错误";

                    return code_response == "0" ? (true, "发送成功") : (false, $"发送失败,{reason}");
                }
                else
                {
                    return (false, $"发送失败,{response}");
                }
            }
            catch (Exception e)
            {
                return (false, e.Message);
            }
        }
    }
}
